import React from "react";
import PropTypes from "prop-types";
import classNames from "classnames";

import "./icon.css";

export default function Icon({ className, type, iconName, url, ...rest }) {
  const name = getName({ type, iconName });

  return (
    <svg className={classNames("icon-svg", className)} {...rest}>
      <use xlinkHref={name}></use>
    </svg>
  );

  function getName({ type = "", iconName = "" } = {}) {
    let name = "file-empty"; // default icon name
    name = `#${name}`;

    if (type) {
      try {
        const { id = "" } = require(`./svg/${type}.svg`).default;
        name = `#${id}`;
      } catch (error) {
        console.error(error);
      }
    } else if (iconName) {
      name = `#${iconName}`;
    } else if (url) {
      name = url;
    }

    return name;
  }
}

Icon.propTypes = {
  className: PropTypes.string,
  type: PropTypes.string,
  iconName: PropTypes.string,
  url: PropTypes.string,
};

Icon.defaultProps = {
  className: "",
  type: "", // 内置icon: inline svg sprite id
  iconName: "", // 自定义icon: inline svg sprite id
  url: "", // 自定义icon: remote svg sprite id
};
